package guestbook;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.google.appengine.api.users.User;

@Entity
//@Table (name = "TB_USER")
@PersistenceContext
@NamedQuery(name="findUserList", query="select u from EntityUser u order by date asc")
public class EntityUser implements Serializable {


	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 5160188724203714131L;

	private static final Logger log = Logger.getLogger(EntityUser.class.getName());
	
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	private String lowno;
	
	private User user;
	private Date date;
	private String content;
	
	public EntityUser(){}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {

		this.user = user;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getLowno() {
		return lowno;
	}
	
	public void setLowno(String lowno) {
		this.lowno = lowno;
	}

	public static List<EntityUser> getEntityUserList(){
		EntityManager em = EMFService.get().createEntityManager();
		try {
			log.log(Level.INFO, "getEntityUserList() 1");
			Query query = em.createNamedQuery("findUserList");
			
			log.log(Level.INFO, "getEntityUserList() 2");
			@SuppressWarnings("unchecked")
			List<EntityUser> list = query.getResultList();
			
			log.log(Level.INFO, "getEntityUserList() 3");
			if(list == null)
			{
				log.log(Level.INFO, "getEntityUserList() NULL");
				return null;
			}
			else
			{
				log.log(Level.INFO, "getEntityUserList() NOT NULL : "+list.size());
				return list;
			}
				
		} catch (Exception e) {
//			log.log(Level.WARNING, "getEntityUserList() : "+e);
			e.printStackTrace();
		} finally {
			em.close();
		}
		
		return null;
	}
	
	public void save()
	{
		EntityManager em = EMFService.get().createEntityManager();
		try {
			em.persist(this);
		} catch (Exception e) {
			log.log(Level.WARNING, "save() : "+e);
		} finally {
			em.close();
		}
	}
	
	public void remove()
	{
		EntityManager em = EMFService.get().createEntityManager();
		try {
			em.remove(this);
		} catch (Exception e) {
			log.log(Level.WARNING, "remove() : "+e);
		} finally {
			em.close();
		}
	}
}
